//
// Created by Tan Ke on 2024/1/14.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

const char* maxInt = "2147483647";
const char* minInt = "2147483648";

int myAtoi(char* s)
{
    int posCnt = 0;
    int negCnt = 0;
    bool isNeg = false;
    bool digitStart = false;
    char str[1024] = {0};
    int index = 0;
    int result = 0;

    memset(str, 0, 1024);

    for (int i = 0; i < strlen(s); i ++) {
        if (s[i] >= '0' && s[i] <= '9') {
            if (digitStart == false) {
                digitStart = true;
            }
            str[index] = s[i];
            index += 1;
        } else {
            if (digitStart == true) {
                break;
            } else {
                if (s[i] == '+') {
                    if (posCnt == 0 && negCnt == 0) {
                        posCnt += 1;
                    } else {
                        return 0;
                    }
                } else if (s[i] == '-') {
                    if (posCnt == 0 && negCnt == 0) {
                        negCnt += 1;
                    } else {
                        return 0;
                    }
                } else if (s[i] == ' ') {
                    if (posCnt == 0 && negCnt == 0) {
                        ;
                    } else {
                        return 0;
                    }
                } else {
                    return 0;
                }
            }
        }
    }

    if (negCnt % 2 != 0) {
        isNeg = true;
    }

    index = 0;
    while (str[index] == '0') {
        index += 1;
    }

    if (strlen(str+index) == 0) {
        return 0;
    }

    if (strlen(str + index) > strlen(minInt)) {
        if (isNeg == true) {
            return -2147483648;
        } else {
            return 2147483647;
        }
    }

    if (strlen(str + index) < strlen(minInt)) {
        for (int i = 0; i < strlen(str + index); i ++) {
            result *= 10;
            result += str[i + index] - '0';
        }
        if (isNeg == true) {
            return -1 * result;
        } else {
            return result;
        }
    }

    if (isNeg == true) {
        if (strncmp(str + index, minInt, strlen(minInt)) >= 0) {
            return -2147483648;
        } else {
            for (int i = 0; i < strlen(str + index); i ++) {
                result *= 10;
                result += str[i + index] - '0';
            }
            return -1 * result;
        }
    } else {
        if (strncmp(str + index, maxInt, strlen(maxInt)) >= 0) {
            return 2147483647;
        } else {
            for (int i = 0; i < strlen(str + index); i ++) {
                result *= 10;
                result += str[i + index] - '0';
            }
            return result;
        }
    }
}

int main(void)
{
    printf("%d\n", myAtoi("4193 with words"));
    printf("%d\n", myAtoi("-91283472332"));
    return 0;
}
